package com.jlnk.aidl_client;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.jlnk.aidl_service.IStudentChangeListener;
import com.jlnk.aidl_service.IStudentService;
import com.jlnk.aidl_service.Student;

import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mTvCount;
    private EditText mEtName;
    private EditText mEtNumber;
    private EditText mEtGrade;
    private EditText mEtAge;
    private EditText mEtRmNumber;
    private Button mBtnAdd;
    private Button mBtnRemove;
    private IStudentService mService;
    private int mStudentCount;
    private Set<Integer> mAddedNumbers; // 用于跟踪已添加的学号
    private boolean mIsBindingService = false;
    private boolean mServiceBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvCount = findViewById(R.id.count);
        mEtName = findViewById(R.id.name);
        mEtNumber = findViewById(R.id.number);
        mEtGrade = findViewById(R.id.grade);
        mEtAge = findViewById(R.id.age);
        mEtRmNumber = findViewById(R.id.rm_number);
        mBtnAdd = findViewById(R.id.add);
        mBtnRemove = findViewById(R.id.remove);
        mTvCount.setOnClickListener(this);
        mBtnAdd.setOnClickListener(this);
        mBtnRemove.setOnClickListener(this);
        mStudentCount = 0; // 初始学生数量为 0
        mAddedNumbers = new HashSet<>(); // 初始化已添加学号的集合
        bindService();
        Button selectAdd = findViewById(R.id.select_add);
        selectAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onQueryClick();
            }
        });
    }

    private void onQueryClick() {
        if (!mServiceBound) {
            Toast.makeText(this, "服务正在绑定，请稍候...", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mService == null) {
            bindService();
            return;
        }
        try {
            // 使用 select_number EditText 中的值来进行查询
            String queryNumberStr = mEtNumber.getText().toString().trim();
            if (queryNumberStr.isEmpty()) {
                Toast.makeText(this, "学号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            int queryNumber = Integer.parseInt(queryNumberStr);
            Student student = mService.selectStudent(queryNumber);
            if (student != null) {
                TextView selectName = findViewById(R.id.select_name);
                TextView selectNumber = findViewById(R.id.select_number);
                TextView selectGrade = findViewById(R.id.select_grade);
                TextView selectAge = findViewById(R.id.select_age);
                selectName.setText(student.getName());
                selectNumber.setText(String.valueOf(student.getNumber()));
                selectGrade.setText(student.getGrade());
                selectAge.setText(String.valueOf(student.getAge()));
            } else {
                Toast.makeText(this, "学生未找到", Toast.LENGTH_SHORT).show();
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字。", Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            Toast.makeText(this, "服务出错。", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIsBindingService) {
            unbindService(mConnection);
        }
    }

    private void bindService() {
        if (!mIsBindingService) { // 检查是否已经在绑定服务
            mIsBindingService = true;
            Intent intent = new Intent();
            intent.setPackage("com.jlnk.aidl_service");
            intent.setAction("com.jlnk.aidl_service.action");
            bindService(intent, mConnection, BIND_AUTO_CREATE);
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IStudentService.Stub.asInterface(service);
            try {
                mService.addListener(mListener);
                mStudentCount = mService.getStudentCount();
                mTvCount.setText(String.valueOf(mStudentCount));
                mServiceBound = true; // 设置服务绑定成功标志
            } catch (RemoteException e) {
                Toast.makeText(MainActivity.this, "服务连接异常", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mServiceBound = false; // 服务断开连接，重置标志
        }
    };

    IStudentChangeListener mListener = new IStudentChangeListener.Stub() {
        @Override
        public void onStudentCountChanged(int count) {
            mStudentCount = count;
            mTvCount.setText(String.valueOf(mStudentCount));
        }
    };

    @Override
    public void onClick(View v) {
        if (!mServiceBound) {
            Toast.makeText(this, "服务正在绑定，请稍候...", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mService == null) {
            bindService();
            return;
        }
        int id = v.getId();
        try {
            if (id == R.id.add) {
                String name = mEtName.getText().toString().trim();
                String numberStr = mEtNumber.getText().toString().trim();
                String grade = mEtGrade.getText().toString().trim();
                String ageStr = mEtAge.getText().toString().trim();

                if (numberStr.isEmpty() || ageStr.isEmpty()) {
                    Toast.makeText(this, "学号和年龄不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                int number = Integer.parseInt(numberStr);
                int age = Integer.parseInt(ageStr);

                if (!mAddedNumbers.contains(number)) { // 检查学号是否已添加
                    Student student = new Student(name, number, grade, age);
                    mService.addStudent(student);
                    mAddedNumbers.add(number); // 记录已添加的学号
                    mStudentCount = mService.getStudentCount(); // 更新学生数量
                    mTvCount.setText(String.valueOf(mStudentCount));
                } else {
                    Toast.makeText(this, "学号已存在。", Toast.LENGTH_SHORT).show();
                }
            } else if (id == R.id.remove) {
                String rmNumberStr = mEtRmNumber.getText().toString().trim();
                if (rmNumberStr.isEmpty()) {
                    Toast.makeText(this, "删除的学号不能为空。", Toast.LENGTH_SHORT).show();
                    return;
                }

                int rm_number = Integer.parseInt(rmNumberStr);
                if (mAddedNumbers.contains(rm_number)) { // 检查学号是否存在
                    mService.deleteStudent(rm_number);
                    mAddedNumbers.remove(rm_number); // 移除已添加的学号
                    mStudentCount = mService.getStudentCount(); // 更新学生数量
                    mTvCount.setText(String.valueOf(mStudentCount));
                } else {
                    Toast.makeText(this, "学号不存在。", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (NumberFormatException | RemoteException e) {
            Toast.makeText(this, "请输入有效的数字。", Toast.LENGTH_SHORT).show();
        }
    }
}